import React, { useState, useEffect } from "react";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig,
  SlateDescendant,
} from "@wangeditor/editor";
import { message } from "antd";
import { asyncossupload } from "../api/api";
import OSS from "ali-oss";
import * as uuid from "uuid";
type InsertFnType = (url: string, alt: string, href: string) => void;


// 扩展 Element
interface SlateElement {
  type: string;
  children: SlateDescendant[];
}

type P = {
  defaultContent?: SlateElement[];
  height: string;
  onChange?: (editor: IDomEditor) => void;
  clear?: boolean;
};

export async function updateoss(files: File[], insert?: (str: string) => void) {
  const res: any = await asyncossupload();
  const client = new OSS({
    region: "oss-cn-qingdao",
    accessKeyId: res.accessKeyId,
    accessKeySecret: res.accessKeySecret,
    stsToken: res.securityToken,
    bucket: "cdn-hterobot",
  });
  const x = files[0].name.split(".");
  const name = x[x.length - 1];
  const url = `www/${uuid.v4()}.${name}`;

  if (insert) {
    const data = await client.put(url, files[0]);
    insert(`https://cdn.hterobot.com/${url}`);
    return data;
  } else {
    return client.put(url, files[0]);
  }
}

function MyEditor(prop: P) {
  const [editor, setEditor] = useState<IDomEditor | null>(null); // 存储 editor 实例
  const [height, setheight] = useState("50px");
  const toolbarConfig: Partial<IToolbarConfig> = {
    /* 工具栏配置 */
    excludeKeys: [
      "lineHeight",
      "italic",
      "fullScreen",
      "todo",
      "redo",
      "undo",
      "numberedList",
      "bgColor",
      "|",
    ],
  };

  // `defaultContent` (JSON 格式) 和 `defaultHtml` (HTML 格式) 二选一
  const defaultContent: SlateElement[] = prop.defaultContent || [];
  // const defaultHtml = '<p>一行文字</p>'
  useEffect(() => {
    editor?.clear();
  }, [prop.clear]);

  const editorConfig: IEditorConfig = {
    placeholder: "请输入内容...",
    onCreated(editor) {
      setEditor(editor);
    },
    customAlert: function (info, type) {
      message[type](info);
    },
    onChange: prop.onChange,
    onFocus: () => {
      setheight("300px");
    },
    onBlur: () => {
      setheight("50px");
    },
    MENU_CONF: {
      bgColor: {
        colors: ["#000", "#333", "#666"],
      },
      uploadImage: {
        customUpload: async function (
          resultFiles: File[] | File,
          insertImgFn: InsertFnType
        ) {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          // 上传图片，返回结果，将图片插入到编辑器中
          const { name } = await updateoss(
            Array.isArray(resultFiles) ? resultFiles : [resultFiles]
          );
          insertImgFn(
            `https://cdn.hterobot.com/${name}`,
            name,
            `https://cdn.hterobot.com/${name}`
          );
        },
      },
      uploadVideo: {
        customUpload: async (
          resultFiles: File | File[],
          insertFn: InsertFnType
        ) => {
          // res 即服务端的返回结果
          const { name } = await updateoss(
            Array.isArray(resultFiles) ? resultFiles : [resultFiles]
          );
          insertFn(
            `https://cdn.hterobot.com/${name}`,
            name,
            `https://cdn.hterobot.com/${name}`
          );
        },
      },
    },
    scroll: false,
    readOnly: false,
    autoFocus: false,
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          defaultContent={defaultContent}
          // defaultHtml={defaultHtml}
          mode="default"
          style={{
            minHeight: height,
            height: "auto",
            overflowY: "auto",
            transition: "all ease-out 0.3s",
          }}
        />
      </div>
    </>
  );
}

export default MyEditor;
